# include "serialib.h"
# include "socat_manager.h"
# include "serial_logger.h"

int main(int argc, char* argv[]) {
    char buffer[1024];
    int bytesRead;

    // 默认配置
    unsigned int baudRate1 = 115200;
    std::string physicalPort1 = "/dev/ttyUSB0";
    std::string virtualTx1 = "/tmp/virtual_tx1";
    std::string virtualRx1 = "/tmp/virtual_rx1";
    std::string logFile1 = "serial_log_1" + 
        std::to_string(std::time(nullptr)) + ".txt";

    unsigned int baudRate2 = 115200;
    std::string physicalPort2 = "/dev/ttyUSB1";
    std::string virtualTx2 = "/tmp/virtual_tx2";
    std::string virtualRx2 = "/tmp/virtual_rx2";
    std::string logFile2 = "serial_log_2" + 
        std::to_string(std::time(nullptr)) + ".txt";
    
    // 解析命令行参数
    if (argc < 9) {
        std::cerr << "用法: " << argv[0] << " [波特率1] [物理端口名称1] [日志文件1] [虚拟端口名称1] [波特率2] [物理端口名称2] [日志文件2] [虚拟端口名称2]" << std::endl;
        return 1;
    }

    try 
    {
        baudRate1 = std::stoi(argv[1]);
    } 
    catch (...) 
    {
        std::cerr << "无效的波特率，使用默认值: " << baudRate1 << std::endl;
    }
    physicalPort1 = argv[2];
    logFile1 = argv[3];
    std::string virtualPort = argv[4];
    virtualTx1 = virtualPort + "_tx";
    virtualRx1 = virtualPort;

    try 
    {
        baudRate2 = std::stoi(argv[5]);
    } 
    catch (...) 
    {
        std::cerr << "无效的波特率，使用默认值: " << baudRate2 << std::endl;
    }
    physicalPort2 = argv[6];
    logFile2 = argv[7];
    virtualPort = argv[8];
    virtualTx2 = virtualPort + "_tx";
    virtualRx2 = virtualPort;
    
    // 注册信号处理函数
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    
    serial_logger m_logger1(baudRate1, physicalPort1, virtualTx1, virtualRx1, logFile1);
    serial_logger m_logger2(baudRate2, physicalPort2, virtualTx2, virtualRx2, logFile2);

    std::cout << "开始转发二进制数据（日志中以十六进制记录），按Ctrl+C停止" << std::endl;
    std::thread p1([&]() -> void {
        m_logger1.run();
    });

    std::thread p2([&]() -> void {        
        m_logger2.run();
    });

    while (running)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    m_logger1.stop();
    m_logger2.stop();

    p1.join();
    p2.join();
    
    std::cout << "程序已退出" << std::endl;

    return 0;
}